package com.asia5b.a5mall.member.fragment

import android.app.Activity
import android.app.ActivityOptions
import android.content.Intent
import android.net.Uri
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.member.R
import com.asia5b.a5mall.member.databinding.FragmentThridloginBinding
import com.asia5b.a5mall.middleware.base.SimpleFragment
import com.asia5b.a5mall.middleware.event.LoginEvent
import com.asia5b.a5mall.middleware.logic.viewmodel.member.ThridLoginFragmentVM
import com.asia5b.a5mall.middleware.model.bean.ConnectLoginBean
import com.asia5b.a5mall.middleware.model.bean.CheckSmsBean
import com.asia5b.a5mall.middleware.model.bean.CheckSmsType
import com.asia5b.a5mall.middleware.utils.*
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import kotlinx.android.synthetic.main.fragment_thridlogin.*

/**
 * Created by zhangyuncai on 2020/4/9.
 * 第三方登录
 *  //todo 第三方登录->已绑定->登录成功
 *  //todo 第三方登录->未绑定绑定->发送短信界面->短信验证界面->登录成功
 */
class ThridLoginFragment : SimpleFragment<ThridLoginFragmentVM, FragmentThridloginBinding>() {
    override val viewModelClazz: Class<ThridLoginFragmentVM>
        get() = ThridLoginFragmentVM::class.java

    override fun getDataBinding(container: ViewGroup?): FragmentThridloginBinding {
        return FragmentThridloginBinding.inflate(layoutInflater,container,false)
    }

    private var connectInfo: ConnectLoginBean? = null

    //绑定并登录吗
    var isAuthBind = false
    val isCanLoginThrid = true
    val listener = object : UMAuthListener {
        override fun onComplete(p0: SHARE_MEDIA, p1: Int, p2: MutableMap<String, String>) {
            dddLog("p2:${p2}")
            dddLog("onComplete")
            when (p0) {
                SHARE_MEDIA.QQ -> {
                    connectInfo = ConnectLoginBean("qq", p2["unionid"]!!)
                    mViewModel.authLogin("qq", p2["unionid"]!!)
                }
                SHARE_MEDIA.WEIXIN -> {
                    /*
                    {country=中国, unionid=oC7jGwm53mX6X1ys3O0lrsxHbkMc, gender=男, city=广州, openid=o_XLLt9x0ZwBkgdu_VLXy0_skKLU, language=zh_CN, profile_image_url=http://thirdwx.qlogo.cn/mmopen/vi_32/MdGkWqia0EzQfTYVvw43lq4MukiayVgjcmQ4OPdicddDwTHTjYtwPsTm4KjODyQGow1bxnBJEgB7oTPDbJYiaxKibLA/132, accessToken=32_nmcjPcLv1UMLbr_NvdzfK39iIr8MhX3D71vgtTqyredEopTeVo0TEebPjX7gwc8jrurtcAcCB7UHkKEXhIlA6zGZNUjLMxYC3V5d3n-vt5k, access_token=32_nmcjPcLv1UMLbr_NvdzfK39iIr8MhX3D71vgtTqyredEopTeVo0TEebPjX7gwc8jrurtcAcCB7UHkKEXhIlA6zGZNUjLMxYC3V5d3n-vt5k, uid=oC7jGwm53mX6X1ys3O0lrsxHbkMc, province=广东, screen_name=张运才, name=张运才, iconurl=http://thirdwx.qlogo.cn/mmopen/vi_32/MdGkWqia0EzQfTYVvw43lq4MukiayVgjcmQ4OPdicddDwTHTjYtwPsTm4KjODyQGow1bxnBJEgB7oTPDbJYiaxKibLA/132, expiration=1586427313919, expires_in=1586427313919, refreshToken=32_K5BsY7uvHYfdLz5-0F-MJq30gz-qjzR_H15RQmMerQYXYUgFr_KezpsUMLDXfGFw9RAPjOUMsly3bgrs_Erpap6VULClVwE3ASZAWEKb0MU}
                     */
                    /*
                    {country=中国, unionid=oC7jGwh_U061bLFlji9CpBpsUCQo, gender=男, city=东莞, openid=o_XLLt8dVRbTomDW9lAk-49CiBWg, language=zh_CN, profile_image_url=http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKlZdprswJgFOoqBZKSoB1KyhmuibwjL5LlXI3WEx0IpUBHyh7hjMVaJrmaTuRgkibgGDgKniaydzQkQ/132, accessToken=32_E60udnAx9SPvRxherp_A35fsfMJO2jB5AZYj8Aq2_IJu43yhnCR5OHs1uSSIWeh2orze5Mp6YaPDR7bRVm48o43CPkGPmEUMqyiikVidf84, access_token=32_E60udnAx9SPvRxherp_A35fsfMJO2jB5AZYj8Aq2_IJu43yhnCR5OHs1uSSIWeh2orze5Mp6YaPDR7bRVm48o43CPkGPmEUMqyiikVidf84, uid=oC7jGwh_U061bLFlji9CpBpsUCQo, province=广东, screen_name=方可为友, name=方可为友, iconurl=http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKlZdprswJgFOoqBZKSoB1KyhmuibwjL5LlXI3WEx0IpUBHyh7hjMVaJrmaTuRgkibgGDgKniaydzQkQ/132, expiration=1586427372494, expires_in=1586427372494, refreshToken=32_JZ_7TiGcgNzQi6Ios21CM-l7YsUVtvhRPqhJ70tIbKUvDjAFmy-TWSRdREpeE9PZkm-KAnkdfg8WzHK35PmX06mJ9wVdR9tTrJfLZI88r6A}
                     */
                    //todo 以前是weixin  朱工让替换为WECHAT
                    connectInfo = ConnectLoginBean("WECHAT", p2["unionid"]!!)
                    mViewModel.authLogin("weixin", p2["unionid"]!!)
                }
                SHARE_MEDIA.SINA -> {
                    connectInfo = ConnectLoginBean("weibo", p2["uid"]!!)
                    mViewModel.authLogin("weibo", p2["uid"]!!)
                }
            }
            //当授权成功后，就取消授权
            UMShareAPI.get(requireContext()).deleteOauth(mActivity, p0, null)
        }

        override fun onCancel(p0: SHARE_MEDIA, p1: Int) {
            showMessage(getString(R.string.取消))
            dddLog("onCancel:${p0.name}")
            //当授权成功后，就取消授权
            UMShareAPI.get(requireContext()).deleteOauth(mActivity, p0, null)
        }

        override fun onError(p0: SHARE_MEDIA, p1: Int, p2: Throwable) {
            dddLog("onError:${p0.name},${p2.message}")
            //当授权成功后，就取消授权
            UMShareAPI.get(mActivity).deleteOauth(mActivity, p0, null)
        }

        override fun onStart(p0: SHARE_MEDIA?) {
            dddLog("onStart:${p0?.name}")
        }
    }


    override fun initView() {
    }

    override fun initEvent() {
        /*
                MD5格式，全小写，不带冒号,修改签名后,微信重新登录即可
                 */

        ll_login_qq.setOnClickListener {
            if (isCanLoginThrid) {
                UMShareAPI.get(mActivity).getPlatformInfo(mActivity, SHARE_MEDIA.QQ, listener)
            } else {
            }
        }
        ll_login_wechat.setOnClickListener {
            if (isCanLoginThrid) {
                UMShareAPI.get(mActivity).getPlatformInfo(mActivity, SHARE_MEDIA.WEIXIN, listener)
            } else {
            }
        }
        ll_login_sina.setOnClickListener {
            if (isCanLoginThrid) {
                UMShareAPI.get(mActivity).getPlatformInfo(mActivity, SHARE_MEDIA.SINA, listener)
            } else {
            }
        }
        ll_login_alipay.setOnClickListener {
            if (isCanLoginThrid) {
                mViewModel.getAlipayAuthInfo(mActivity)
            } else {
            }
        }
        ll_login_jy.setOnClickListener {
            val appPackage = "com.wushiyi.asia5b.jiyun"
            if (AppUtil.isAppInstall(mActivity, appPackage)) {
                val uri = Uri.parse("asia5bjy://profile/")
                val intent = Intent(Intent.ACTION_VIEW, uri)
                startActivityForResult(intent, 82, ActivityOptions.makeSceneTransitionAnimation(mActivity).toBundle())
//                startActivityForResult(intent, 82)
            } else {
                showMessage(R.string.应用未安装)
            }
        }
    }

   override fun startObserver()
    {
        mViewModel.authLoginErrorLiveData.observe(this, Observer {
            authLoginError()
        })
        mViewModel.loginSuccessResultLiveData.observe(this, Observer {
            loginSuccessResult()
        })
    }

    /**
     * 登录并绑定第三方uid
     */
    fun authBind(username: String, password: String, imageCode: String) {
        mViewModel.authBind(connectInfo!!, username, password, imageCode)
    }

    override fun lazyFetchData() {

    }


    fun authLoginError() {
        push(ActCons.RegisterActivity, { postcard ->
            postcard.withSerializable("type", CheckSmsBean(CheckSmsType.REGISTER_USER_OR_BIND_PHONE).apply {
                this.connectInfo = this@ThridLoginFragment.connectInfo
            })
        })
        mActivity.finish()
    }

    fun loginSuccessResult() {
        getEventBus().post(LoginEvent())
        mActivity.pop()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 82) {
                if (data != null && data!!.hasExtra("profile")) {
                    val profile = data!!.getSerializableExtra("profile") as HashMap<String, Any>
                    connectInfo = ConnectLoginBean("ASIAJY", "${profile.get("uid")}")
                    mViewModel.authLogin("ASIAJY", "${profile.get("uid")}")
                }
            }
        }
    }

}